package handle

import (
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/core/command"
	"gitee.com/crack007/goose/injection"
	"gitee.com/crack007/goose/rpc"
	"github.com/crack007/go-im/pb"
	"github.com/crack007/go-im/src/common/config"
	"github.com/crack007/go-im/src/module/sentinel/service"
	"google.golang.org/grpc"
)

type SentinelHandle struct {
	command.DefaultCmdHandle
	MasterIp   string
	MasterPort uint16
}

func NewSentinelHandle() *SentinelHandle {
	return &SentinelHandle{}
}

func (h *SentinelHandle) OnInitConfig() {
	config.InitAppConfig()
	service.SentinelService.CurrentNode.Ip = config.GetNodeConfig().NodeAddr
	service.SentinelService.CurrentNode.Id = config.GetNodeConfig().NodeName
}
func (h *SentinelHandle) OnInitInject() []injection.Service {
	return []injection.Service{injection.GRPC_SERVER_SERVICE, injection.SCHEDULE_SERVICE, injection.REDIS_SERVICE}
}

func (h *SentinelHandle) OnRun() error {

	rpcServer := rpc.GetServer("sentinel")
	service.SentinelService.CurrentNode.Port = rpcServer.Port
	go func() {
		rpcServer.SetRegisterServer(func(grpcServer *grpc.Server) {
			pb.RegisterSentinelServiceServer(grpcServer, service.GrpcService)
		})
		service.SentinelService.AddSentinelNode(service.SentinelService.CurrentNode)
		// 和master节点建立连接
		err := service.SentinelService.ConnectMaster(h.MasterIp, h.MasterPort)
		if err != nil {
			goose.GetLogger().Error("Connect to master fail->%s", err.Error())
			return
		}
	}()
	go service.SentinelService.VoteProcess()
	return rpcServer.Bootstrap(h.GetCmd().Ctx)
}
